package com.example.side_pull_menu.Fragment;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.side_pull_menu.Fragment8kj;
import com.example.side_pull_menu.MySqliteOpenHelper;
import com.example.side_pull_menu.R;
import com.google.gson.Gson;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;

import static android.support.constraint.Constraints.TAG;

public class Fragment_8 extends Fragment{
    private SQLiteDatabase db;
    private TextView tv_balance;
    private Spinner spinner;
    private EditText et_recharge;
    private Button bu_query;
    private Button bu_recharge;
    private int i=0;
    private ListView lv;
    private List<Fragment8kj>fragment8kjs=new ArrayList<>();
   // private List<Fragment8kj.DataBean> fragment8kjss=new ArrayList<Fragment8kj.DataBean>();
    public Fragment_8() {
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_8, container, false);
        initView(view);
        initData();
        bu_recharge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initData1();
            }
        });
        return view;
    }
    public interface BlogService{
        @GET("carlist")
        Call<ResponseBody>getBlog();
    }
    public interface BlogService1{
        @POST("charge")
        Call<ResponseBody>getBlog(@Body RequestBody user);
    }
    private void initData1 (){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://hh1.me:5001/")
                .build();
        Map<String,String> map = new HashMap<>();
        map.put("who",fragment8kjs.get(0).getData().get(i).getWho());
        map.put("carno",fragment8kjs.get(0).getData().get(i).getCarno());
        map.put("amount",et_recharge.getText().toString().trim());
        Gson gson = new Gson();
        Log.d(TAG, "initData1: "+ gson.toJson(map));
        RequestBody requestBody = RequestBody.create(gson.toJson(map),MediaType.parse("application/json;charset=utf-8"));
        BlogService1 service = retrofit.create(BlogService1.class);
        Call<ResponseBody> call = service.getBlog(requestBody);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (TextUtils.isEmpty(et_recharge.getText().toString().trim())){
                    Toast.makeText(getContext(), "充值金额不能为空", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(getContext(), "充值成功", Toast.LENGTH_SHORT).show();
                    //创建一个帮助类对象
                    MySqliteOpenHelper mySqliteOpenHelper = new MySqliteOpenHelper(getContext());
                    //调用getReadableDatabase方法,来初始化数据库的创建
                    db= mySqliteOpenHelper.getReadableDatabase();
                    //把数据存放到数据库
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm");
                    Date date = new Date(System.currentTimeMillis());
                    ContentValues values=new ContentValues();
                    values.put("_id",i+1);
                    values.put("time",simpleDateFormat.format(date));
                    values.put("carno",fragment8kjs.get(0).getData().get(i).getCarno());
                    values.put("name",fragment8kjs.get(0).getData().get(i).getWho());
                    values.put("amount",et_recharge.getText().toString());
//                        values.put("rechargeamount",fragment8kjs.get(0).getData().get(i).getCharge());
                    db.insert("info",null,values);
                }
                initData();
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }
    private void initView(View view) {
        lv=(ListView)view.findViewById(R.id.lv);
        tv_balance = (TextView) view.findViewById(R.id.tv_balance);
        spinner = (Spinner) view.findViewById(R.id.spinner);
        et_recharge = (EditText) view.findViewById(R.id.et_recharge);
        bu_query = (Button) view.findViewById(R.id.bu_query);
        bu_recharge = (Button) view.findViewById(R.id.bu_recharge);
        et_recharge.addTextChangedListener(mTextWatcher);
    }
    //判断输入款输入的数值是否以0开头
    private TextWatcher mTextWatcher=new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int i, int i1, int i2) {
        }
        @Override
        public void onTextChanged(CharSequence s, int i, int i1, int i2) {
        }
        @Override
        public void afterTextChanged(Editable s) {
            String text= s.toString();
            int len=s.toString().length();
            if (len==1 && text.equals("0")){
                s.clear();
                Toast.makeText(getContext(),"金额不能以0开头，请重新输入",Toast.LENGTH_LONG).show();
            }
        }
    };
    private void initData(){
        Retrofit retrofit=new Retrofit.Builder()
                .baseUrl("http://hh1.me:5001")
                .build();
        BlogService service=retrofit.create(BlogService.class);
        Call<ResponseBody>call=service.getBlog();
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    Gson gson = new Gson();
                    Fragment8kj carlist = gson.fromJson(response.body().string(), Fragment8kj.class);
                    //spinner的用法
                    fragment8kjs.add(carlist);
                    tv_balance.setText("账户余额:"+fragment8kjs.get(0).getData().get(i).getAmount()+"元");
                    final String[] sspinner=getResources().getStringArray(R.array.license);
                    ArrayAdapter<String>adapter=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_dropdown_item,sspinner);
                    spinner.setAdapter(adapter);
                    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> adapterView, View view, final int j, long l) {
                            i=j;
                            bu_query.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    tv_balance.setText("账户余额:"+fragment8kjs.get(0).getData().get(i).getAmount()+"元");
                                }
                            });
                        }
                        @Override
                        public void onNothingSelected(AdapterView<?> adapterView) {

                        }
                    });
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });
    }
}